<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,
        addBtn: false,
      }"
      :table-props="{
        selection: true,
        delBtn: true,
        viewBtn: false,
        editBtn: true,
        menuSlot: true,
        menuWidth: 300,
        tableLayout: 'fixed',
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
      @change="onChange"
    >
      <template #leftToolbar>
        <el-button class=" mr5" type="primary" icon="Plus" @click="handleBatchAdd">{{t('system.chargerStorage.action.add')}}</el-button>
        <el-dropdown class="mt-[1px]" v-if="multipleSelection.length > 0">
          <el-button plain
            >批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon
          ></el-button>
          <template #dropdown>
            <el-dropdown-item icon="Delete">
              <template #default>
                <el-popconfirm :title="t('operate.confirm.batchDelete')" @confirm="handleBatchDelete">
                  <template #reference> {{t('crud.batchDeleteText')}} </template>
                </el-popconfirm>
              </template>
            </el-dropdown-item>
            <el-dropdown-item icon="RefreshLeft" @click="handleBatchStore(multipleSelection.map(element => element.id))">{{t('system.chargerStorage.action.store')}}</el-dropdown-item>
          </template>
        </el-dropdown>
      </template>
      <template #rightToolbar></template>

      <template #menuSlot="scope:any">
        <el-tooltip class="box-item" effect="dark" :content="t('system.chargerStorage.action.store')" placement="top">
          <div class="menu-btn">
            <el-button type="primary" link icon="RefreshLeft" @click="handleBatchStore([scope.row.id])" />
          </div>
        </el-tooltip>
      </template>
    </yt-crud>
    <BatchForm ref="batchFormRef" @success="handleSuccess" />
    <StoreForm ref="storeFormRef" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import { storageList, storageSave, storageDelete, storageBatchDelete} from '@/api/system/storage'
import {optionSelect as productOptionSelect} from '@/api/platform/product'
import YtCrud from '@/components/common/yt-crud.vue'
import {useI18n} from 'vue-i18n'
import BatchForm from '@/views/system/storage/modules/BatchForm.vue'
import StoreForm from '@/views/system/storage/modules/StoreForm.vue'
import {ElPopconfirm} from 'element-plus'
const { t } = useI18n()

const state = reactive({
  page: {
    pageSize: 30,
    pageNum: 1,
    sortMap: { name: 'asc', dn: 'asc', createTime: 'desc'},
  },
  total: 0,
  loading: false,
  query: {},
})

const batchFormRef = ref()
const storeFormRef = ref()

// 产品字典
const productOptions = ref<any[]>([])

const formProps = ref({
  width: 600,
})

const column = ref<IColumn[]>([
  {
    label: t('system.chargerStorage.productKey'),
    key: 'productKey',
    type: 'select',
    search: true,
    editDisabled: true,
    colSpan: 22,
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'id',
      options: [],
    },
  },
  {
    label: t('system.chargerStorage.name'),
    key: 'name',
    search: true,
  },
  {
    label: t('system.chargerStorage.dn'),
    key: 'dn',
    search: true,
    sortable: true,
  },
  {
    label: t('system.chargerStorage.note'),
    key: 'note',
    hide: true,
    formHide: false,
    componentProps: {
      type: 'textarea',
      rows: 2,
    }
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  storageList({
    ...state.page,
    ...state.query,
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

const getDict = () => {
  productOptionSelect({type: 'Charger', status: 'Enabled' }).then((res) => {
    productOptions.value = res.data || []
    column.value.forEach((item) => {
      if (item.key === 'productKey') {
        item.componentProps.options = productOptions.value.map((item)=> {
          return {id: item.productKey, name: item.name}
        })
      }
    })
  })
}
getDict()

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  await storageSave(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.loading = false
  })
}
// 弹窗前置操作
const openBeforeFun = ({ type }) => {
  if (type === 'add') { /* empty */ } else if (type === 'update') { /* empty */ }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  storageDelete(row.id).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handleBatchDelete = () =>{
  state.loading = true
  storageBatchDelete(multipleSelection.value.map(element => element.id)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handleBatchStore = (ids: any[]) =>{
  storeFormRef.value.openDialog(ids)
}


const multipleSelection = ref<any[]>([])

const onChange = (data: any) => {
  multipleSelection.value = data
}

const handleBatchAdd = async () => {
  batchFormRef.value.openDialog()
}

const handleSuccess = ()=>{
  getData()
}

const options = reactive({
  ref: 'crudRef',
  formProps,
  data,
  column,
})
</script>
